// pages/my/good.js
const app = getApp();
const qiniuUploader = require("../../qiniu.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    good: {},
    id: 0,
    chooseImg: false,
    imgPath: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.getGoodInfo()
    }
  },
  getGoodInfo(){
    let that = this;
    if (that.data.id > 0) {
      app.request('/api/wx/goodInfo', {
        'id' : that.data.id
      }, (data)=>{
        that.setData({
          good: data
        });
      });
    }
  },
  setValue(key, value){
    let good = this.data.good;
    good[key] = value;
    this.setData({
      good: good
    });
  },
  gname(e){
    this.setValue('sg_title', e.detail.value);
  },
  gprice(e){
    this.setValue('sg_price', e.detail.value);
  },
  gsummary(e){
    this.setValue('sg_summary', e.detail.value);
  },
  selImg(){
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        that.setData({
          chooseImg: true,
          imgPath: res.tempFilePaths[0]
        })
      },
    })
  },
  submit(){
    let that = this;
    if (this.data.chooseImg) {
      qiniuUploader.upload(that.data.imgPath, (res) => {
        that.data.good.sg_img = res.imageURL
        that.setData({
          chooseImg: false
        })
        that.doSubmit();
      }, () => { }, {
        uptoken: app.globalData.upToken,
        region: 'z0',
        domain: '',
      });
    } else {
      that.doSubmit();
    }
  },
  doSubmit(){
    let good = this.data.good;
    if (this.data.id > 0) {
      good['sg_id'] = this.data.id
    }
    app.request('api/wx/saveGood', good, (data, msg)=>{
      wx.showToast({
        title: msg,
      })
      wx.navigateBack({
        delta: 1
      })
    });
  }
})